package helper

import (
	"errors"
	"regexp"
	"strings"
)

/**
 * 验证
 * 2020/08/10
 */

type Validate struct {
	Data  []interface{}
	Title []string
	Rule  []string //多个规则使用逗号(,)隔开
}

func (v *Validate) Check() error {
	if len(v.Data) == 0 {
		return nil
	}
	if len(v.Data) != len(v.Title) || len(v.Data) != len(v.Rule) {
		return errors.New("验证参数不对应")
	}
	msg := make([]string, 0)
	var ok bool
	for key, data := range v.Data {
		rules := strings.Split(v.Rule[key], ",") //分隔所有规则
		for _, rule := range rules {
			switch rule {
			case "require":
				ok = require(data)
				if !ok {
					msg = append(msg, StringJoin(v.Title[key], "不能为空"))
				}
			}
		}
	}
	if len(msg) == 0 {
		return nil
	}
	return errors.New(strings.Join(msg, ","))
}

func require(data interface{}) bool {
	if ToString(data) == "" {
		return false
	}
	return true
}

// 判断手机号码
func IsMobile(mobile string) bool {
	result, _ := regexp.MatchString(`^(1[3|4|5|6|7|8]\d{9})$`, mobile)
	if result {
		return true
	} else {
		return false
	}
}

// 判断邮箱
func IsEmail(email string) bool {
	pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱
	reg := regexp.MustCompile(pattern)
	return reg.MatchString(email)
}
